import sqlite3
from flask import Flask, redirect, url_for, render_template, request, session


def SetFunctions(app):
    # 注册用户到数据库并返回userid
    def register_user_to_db(username, password):
        con = sqlite3.connect('./users.db')
        cur = con.cursor()
        cur.execute('SELECT username FROM users WHERE username=?', [username])
        existing_user = cur.fetchone()
        if existing_user:
            con.close()
            return "user-exists"

        cur.execute('INSERT INTO users(username, password) VALUES (?, ?)', (username, password))
        con.commit()
        con.close()
        return None

    # 检查用户是否存在并验证密码
    def check_user(username, password):
        con = sqlite3.connect('./users.db')
        cur = con.cursor()
        cur.execute('SELECT userid FROM users WHERE username=? AND password=?', (username, password))

        result = cur.fetchone()
        con.close()
        if result:
            return result[0]
        else:
            return None

    @app.route("/")
    def index():
        return render_template('login.html')


    @app.route('/register', methods=["POST", "GET"])
    def register():
        if request.method == 'POST':
            # data = request.get_json()  # 获取JSON格式的数据
            # username = data.get('username')
            # password = data.get('password')

            username = request.form['username']
            password = request.form['password']

            if username == "" or password == "":
                return render_template("register.html", regis_state="input-none")

            with sqlite3.connect("users.db") as usersDB:
                cur = usersDB.execute("SELECT userid FROM users WHERE username=?", [username])
                db_result = cur.fetchone()
                print(db_result)
                # print("testetst")
            # 读取用户数据库
            if db_result is not None:  # 此时用户存在
                return render_template("register.html", regis_state="user-exist")

            # 保存账户信息
            register_user_to_db(username, password)
            return redirect(url_for('index'))

        else:
            return render_template('register.html')

    @app.route('/login', methods=["POST", "GET"])
    def login():
        if request.method == 'POST':
            username = request.form['username']
            password = request.form['password']

            with sqlite3.connect("users.db") as usersDB:
                cur = usersDB.execute("SELECT password, userid FROM users WHERE username=?", [username])
                db_result = cur.fetchone()

            if db_result is None:  # 用户不存在
                return render_template("login.html", login_state="user-not-exist")

            if password != db_result[0]:  # 密码错误
                return render_template("login.html", login_state="password-error")

            # 验证成功，存储用户id到session中
            session['username'] = username
            session['userid'] = db_result[1]
            return redirect(url_for('home'))
        else:
            return render_template('login.html')

    @app.route('/home', methods=['POST', "GET"])
    def home():
        if 'username' in session and 'userid' in session:
            return render_template('home.html', username=session['username'], userid=session['userid'])
        return render_template('home.html')

    @app.route('/logout')
    def logout():

        session.clear()
        return redirect(url_for('index'))
